"ui";
ui.layoutFile('./ui.xml');

ui.xfc.on("check", function (checked) {
    if (checked && !floaty.checkPermission()) {
        ui.xfc.checked = false;
        toast("请先开启悬浮窗权限!");
        floaty.requestPermission();
        return;
    }else if(checked){
        XFC();
    }
});
ui.rizhi.on("click", function () {//查看日志
    app.startActivity("console");
});
threads.start(()=> {
    // 请求截图
    if(!requestScreenCapture()){
        toast("请求截图失败");
        exit();
    }
});
const MAIN = ()=>{
    let img = captureScreen();
    let ocr = $ocr.create({
        models: "slim",//指定精度
    });
    let res = ocr.detect(img);
    ocr.release();
    img.recycle();
    let txt = '';
    for (var x = 0; x < res.length; x++) {
        txt+='|'+res[x].text;
    }
    toast(txt);
    console.log(res);
}


const XFC = function(main){//悬浮球
    threads.start(()=> {
        this.window = floaty.window('<frame w="44" h="44" alpha="1" id="action"><img w="44" h="44" src="#FFFFFF" circle="true" /><img w="28" h="28" src="@drawable/ic_play_arrow_black_48dp"  tint="#41A4F5" gravity="center" layout_gravity="center" id="icon" /></frame>');
        this.window.setPosition(0,device.height / 2 );
        //记录按键被按下时的触摸坐标
        var x = 0,
            y = 0;
        //记录按键被按下时的悬浮窗位置
        var windowX, windowY;
        //记录按键被按下的时间以便判断长按等动作
        var downTime;
        let op = this;
        this.window.action.setOnTouchListener(function(view, event) {
            switch (event.getAction()) {
                case event.ACTION_DOWN:
                    x = event.getRawX();
                    y = event.getRawY();
                    windowX = op.window.getX();
                    windowY = op.window.getY();
                    downTime = new Date().getTime();
                    return true;
                case event.ACTION_MOVE:
                    //移动手指时调整悬浮窗位置
                    op.window.setPosition(windowX + (event.getRawX() - x),
                        windowY + (event.getRawY() - y));
                    //如果按下的时间超过1.5秒判断为长按，退出脚本
                    if (new Date().getTime() - downTime > 1500) {
                        exit();
                    }
                    return true;
                case event.ACTION_UP:
                    //手指弹起时如果偏移很小则判断为点击
                    if (Math.abs(event.getRawY() - y) < 5 && Math.abs(event.getRawX() - x) < 5) {
                        onClick();
                    }
                    return true;
            }
            return true;
        });
        
        function onClick() {
            MAIN();
        }
    });
}